package com.net.toooen.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.net.toooen.api.request.DownPhonenoRequest;
import com.net.toooen.api.request.LoginRequest;
import com.net.toooen.api.request.UserInfoRequest;
import com.net.toooen.api.response.Response;
import com.net.toooen.api.response.ResultResponse;
import com.net.toooen.service.AppInterfaceService;
import com.net.toooen.util.JsonUtil;

@Service
public class AppInterfaceServiceImpl implements AppInterfaceService {

	@Override
	public Response login(LoginRequest request) {
		Record record = null;
		String sql = "select id,allNum,useNum from user where isEnabled = true and username = ? and password = ?";
		record = Db.findFirst(sql,request.getLoginName(),request.getPassword());
		if(null == record){
			return new Response(Response.CODE_FAIL,"用户名或密码错误.");
		}
		
		ResultResponse resp = new ResultResponse();
		resp.getResultMap().put("userInfo", JsonUtil.getMapByJfinalRecord(record));
		return resp;
	}

	@Override
	public Response downPhoneno(final DownPhonenoRequest req) {
		final ResultResponse resp = new ResultResponse();
		
	    boolean falg = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				List<Record> records = new ArrayList<Record>();
				String sql = "select id,phoneName,phoneNo from phoneno where status = 1 and  userId = ? limit ?";
				records = Db.find(sql,req.getUserId(),req.getPhoneNoCount());
				
				sql = "update phoneno set status = 2 where id = ?";
				//更新手机号状态
				for(Record record : records){
					Db.update(sql,record.getInt("id"));
					record.remove("id");
				}
				
				//更新用户下载数
				sql = "update user set useNum = useNum + ? where id = ?";
				Db.update(sql,req.getPhoneNoCount(),req.getUserId());
				
				resp.getResultMap().put("phoneNoList", JsonUtil.getJsonObjByjfinalList(records));
				return true;
			}
		});
	    
	    if(falg){
	    	return resp;
	    }else{
	    	return Response.ERROR_SERVER;
	    }
		
	}

	@Override
	public Response userInfo(UserInfoRequest req) {
		String sql = "select id,allNum,useNum from user where id = ?";
		Record record = Db.findFirst(sql,req.getUserId());
		ResultResponse resp = new ResultResponse();
		resp.getResultMap().put("userResource", JsonUtil.getMapByJfinalRecord(record));
		return resp;
	}
	
}